﻿@using Microsoft.Extensions.Configuration
@using Microsoft.Extensions.DependencyInjection
@using Microsoft.Extensions.Logging
@using SendGrid
@using System.Text.Json
@if ( Small )
{
    <Row>
        <Column>
            @if ( ShowHeading )
            {
                <Heading Size="HeadingSize.Is5">
                    Be the first to get updates
                </Heading>
            }
            <Validations @ref="@validationsRef" Mode="ValidationMode.Manual" ValidateOnLoad>
                <Validation Validator="ValidationRule.IsEmail">
                    <Field>
                        <FieldBody>
                            <Addons>
                                <Addon AddonType="AddonType.Body">
                                    <TextEdit Role="TextRole.Email" Placeholder="Email Address" @bind-Text="@email">
                                    </TextEdit>
                                </Addon>
                                <Addon AddonType="AddonType.End">
                                    <Button Color="Color.Primary" Clicked="@OnSubscribeClicked">Subscribe</Button>
                                </Addon>
                                <ValidationError Style="font-size: .85rem;">Please complete this required field.</ValidationError>
                            </Addons>
                        </FieldBody>
                    </Field>
                </Validation>
            </Validations>
            @if ( emailSent )
            {
                <Alert Color="Color.Success" Visible Style="font-size: .85rem;">
                    <AlertDescription>
                        Thank you for subscribing.
                    </AlertDescription>
                </Alert>
            }
        </Column>
    </Row>
}
else
{
    <Row>
        <Column>
            <Card Shadow="Shadow.Default">
                <CardBody>
                    @if ( ShowHeading )
                    {
                        <Heading Size="HeadingSize.Is5">
                            Be the first to get updates
                        </Heading>
                    }
                    <Validations @ref="@validationsRef" Mode="ValidationMode.Manual" ValidateOnLoad>
                        <Validation Validator="ValidationRule.IsEmail">
                            <Field>
                                <FieldBody>
                                    <TextEdit Role="TextRole.Email" Placeholder="Email Address" @bind-Text="@email">
                                        <Feedback>
                                            <ValidationError Style="font-size: .8rem;">Please complete this required field.</ValidationError>
                                        </Feedback>
                                    </TextEdit>
                                </FieldBody>
                            </Field>
                            <Paragraph Style="font-size: .8rem;">
                                Blazorise needs the contact information you provide to contact you about our products and services. You may unsubscribe from these communications at anytime. For information on how to unsubscribe, as well as our privacy practices and commitment to protecting your privacy, check out our <Anchor To="privacy" Title="Link to Privacy Policy">Privacy Policy</Anchor>.
                            </Paragraph>

                            <Button Color="Color.Primary" Clicked="@OnSubscribeClicked" Block>Stay up to date</Button>
                        </Validation>
                    </Validations>
                    @if ( emailSent )
                    {
                        <Alert Color="Color.Success" Visible Style="font-size: .8rem;" Margin="Margin.Is3.FromTop.Is0.FromBottom">
                            <AlertDescription>
                                Thank you for subscribing.
                            </AlertDescription>
                        </Alert>
                    }
                </CardBody>
            </Card>
        </Column>
    </Row>
}
@code {
    Validations validationsRef;
    string email;
    bool emailSent;

    [Parameter] public bool ShowHeading { get; set; } = true;

    [Parameter] public bool Small { get; set; }

    [Inject] public ILogger<NewsletterWidget> Logger { get; set; }

    [Inject] public IConfiguration Configuration { get; set; }

    async Task OnSubscribeClicked()
    {
        emailSent = false;

        try
        {
            if ( await validationsRef.ValidateAll() )
            {
                var apiKey = Configuration["SendGrid:ApiKey"];

                var content = JsonSerializer.Serialize( new
                {
                    list_ids = new[] { Configuration["SendGrid:ListId"] },
                    contacts = new[] { new { email = email } }
                } );

                var sendGridClient = new SendGridClient( apiKey );

                var response = await sendGridClient.RequestAsync( BaseClient.Method.PUT, content, null, "marketing/contacts" );

                if ( response.IsSuccessStatusCode )
                {
                    email = null;
                    emailSent = true;
                }

                await validationsRef.ClearAll();
            }
        }
        catch ( Exception exc )
        {
            Logger.LogError( exc.Message );
        }
    }
}
